<template>
  <CustomerLayout>
    <div class="order-review-container">
      <!-- 页面标题 -->
      <div class="page-header">
        <el-button 
          link 
          @click="goBack" 
          class="back-btn"
        >
          <el-icon><ArrowLeft /></el-icon>
          返回
        </el-button>
        <h2>评价订单</h2>
      </div>

      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <el-icon class="is-loading" size="40"><Loading /></el-icon>
        <p>加载中...</p>
      </div>

      <!-- 评价内容 -->
      <div v-else-if="orderInfo.id" class="review-content">
        <!-- 订单信息 -->
        <div class="order-info-section">
          <div class="section-title">
            <el-icon><List /></el-icon>
            订单信息
          </div>
          <div class="order-summary">
            <div class="store-info">
              <el-image 
                :src="storeInfo.logo || storeInfo.coverImage" 
                fit="cover"
                class="store-logo"
              >
                <template #error>
                  <div class="image-placeholder">
                    <el-icon><Picture /></el-icon>
                  </div>
                </template>
              </el-image>
              <div class="store-details">
                <div class="store-name">{{ storeInfo.name }}</div>
                <div class="order-time">{{ formatTime(orderInfo.createTime) }}</div>
              </div>
              <div class="order-amount">¥{{ orderInfo.totalAmount?.toFixed(2) }}</div>
            </div>
            
            <!-- 商品列表简化显示 -->
            <div class="items-summary">
              <span class="items-count">{{ orderInfo.items?.length || 0 }}件商品</span>
              <el-button link size="small" @click="showItemsDetail = !showItemsDetail">
                {{ showItemsDetail ? '收起' : '查看详情' }}
                <el-icon><ArrowDown v-if="!showItemsDetail" /><ArrowUp v-else /></el-icon>
              </el-button>
            </div>
            
            <!-- 展开的商品详情 -->
            <div v-show="showItemsDetail" class="items-detail">
              <div v-for="item in orderInfo.items" :key="item.id" class="item-detail">
                <el-image 
                  :src="item.foodImage" 
                  :alt="item.foodName"
                  fit="cover"
                  class="item-image"
                >
                  <template #error>
                    <div class="image-placeholder">
                      <el-icon><Picture /></el-icon>
                    </div>
                  </template>
                </el-image>
                <div class="item-info">
                  <div class="item-name">{{ item.foodName }}</div>
                  <div class="item-meta">
                    <span class="quantity">x{{ item.quantity }}</span>
                    <span class="price">¥{{ (item.subtotal || (item.price * item.quantity)).toFixed(2) }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 评价表单 -->
        <div class="review-form-section">
          <div class="section-title">
            <el-icon><Star /></el-icon>
            评价订单
          </div>
          
          <el-form :model="reviewForm" :rules="reviewRules" ref="reviewFormRef" label-width="100px">
            <!-- 商家评分 -->
            <el-form-item label="商家评分" prop="storeRating" required>
              <div class="rating-container">
                <el-rate
                  v-model="reviewForm.storeRating"
                  :max="5"
                  :colors="['#ff9900', '#ff9900', '#ff9900']"
                  show-score
                  score-template="{value} 分"
                />
                <div class="rating-desc">{{ getRatingDesc(reviewForm.storeRating) }}</div>
              </div>
            </el-form-item>

            <!-- 配送评分 -->
            <el-form-item label="配送评分" prop="riderRating" required>
              <div class="rating-container">
                <el-rate
                  v-model="reviewForm.riderRating"
                  :max="5"
                  :colors="['#ff9900', '#ff9900', '#ff9900']"
                  show-score
                  score-template="{value} 分"
                />
                <div class="rating-desc">{{ getRatingDesc(reviewForm.riderRating) }}</div>
              </div>
            </el-form-item>

            <!-- 评价内容 -->
            <el-form-item label="评价内容" prop="content">
              <el-input
                v-model="reviewForm.content"
                type="textarea"
                :rows="4"
                placeholder="请分享您的用餐体验，您的评价对其他用户很有帮助"
                maxlength="500"
                show-word-limit
              />
            </el-form-item>

            <!-- 上传图片 -->
            <el-form-item label="上传图片">
              <div class="image-upload-section">
                <el-upload
                  v-model:file-list="imageList"
                  action="#"
                  list-type="picture-card"
                  :auto-upload="false"
                  :on-change="handleImageChange"
                  :on-remove="handleImageRemove"
                  :before-upload="beforeImageUpload"
                  accept="image/*"
                  :limit="5"
                >
                  <el-icon><Plus /></el-icon>
                </el-upload>
                <div class="upload-tip">最多上传5张图片，支持jpg、png格式</div>
              </div>
            </el-form-item>

            <!-- 快捷评价标签 -->
            <el-form-item label="快捷评价">
              <div class="quick-tags">
                <el-tag
                  v-for="tag in quickTags"
                  :key="tag"
                  :type="selectedTags.includes(tag) ? 'primary' : 'info'"
                  :effect="selectedTags.includes(tag) ? 'dark' : 'plain'"
                  @click="toggleTag(tag)"
                  class="tag-item"
                >
                  {{ tag }}
                </el-tag>
              </div>
            </el-form-item>
          </el-form>
        </div>
      </div>

      <!-- 底部操作栏 -->
      <div v-if="orderInfo.id" class="action-bar">
        <el-button size="large" @click="goBack" class="cancel-btn">
          取消
        </el-button>
        <el-button 
          type="primary" 
          size="large" 
          @click="submitReview"
          :loading="submitting"
          class="submit-btn"
        >
          {{ submitting ? '提交中...' : '提交评价' }}
        </el-button>
      </div>

      <!-- 空状态 -->
      <div v-else-if="!loading" class="empty-state">
        <EmptyState message="订单信息加载失败" />
      </div>
    </div>
  </CustomerLayout>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, reactive } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage, ElMessageBox, FormInstance, FormRules, UploadFile, UploadFiles } from 'element-plus';
import { 
  ArrowLeft, 
  List,
  Picture,
  Star,
  Plus,
  Loading,
  ArrowDown,
  ArrowUp
} from '@element-plus/icons-vue';
import CustomerLayout from "@/components/customer/CustomerLayout.vue";
import EmptyState from "@/components/common/EmptyState.vue";
import { orderApi, storeApi } from '@/api/customer';
import type { Order, Store } from '@/types/customer';

const router = useRouter();
const route = useRoute();

// 响应式数据
const loading = ref(true);
const submitting = ref(false);
const showItemsDetail = ref(false);
const orderInfo = ref<Partial<Order>>({});
const storeInfo = ref<Partial<Store>>({});
const reviewFormRef = ref<FormInstance>();
const imageList = ref<UploadFile[]>([]);
const selectedTags = ref<string[]>([]);

// 评价表单
const reviewForm = reactive({
  storeRating: 5,
  riderRating: 5,
  content: ''
});

// 表单验证规则
const reviewRules: FormRules = {
  storeRating: [
    { required: true, message: '请为商家评分', trigger: 'change' }
  ],
  riderRating: [
    { required: true, message: '请为配送评分', trigger: 'change' }
  ]
};

// 快捷评价标签
const quickTags = [
  '味道不错', '分量足', '包装精美', '送餐及时', '态度良好',
  '性价比高', '食材新鲜', '口感很棒', '物流给力', '推荐购买'
];

// 页面初始化
onMounted(() => {
  loadOrderDetail();
});

// 加载订单详情
const loadOrderDetail = async () => {
  try {
    loading.value = true;
    const orderId = Number(route.params.id);
    
    if (!orderId || isNaN(orderId)) {
      ElMessage.error('无效的订单ID');
      return;
    }
    
    const response = await orderApi.getOrderDetail(orderId);
    
    // 处理API响应结构
    let orderData: any = null;
    if ((response as any).id) {
      orderData = response;
    } else if ((response as any).data && (response as any).data.id) {
      orderData = (response as any).data;
    } else if ((response as any).data && (response as any).data.data && (response as any).data.data.id) {
      orderData = (response as any).data.data;
    }
    
    if (orderData && orderData.id) {
      // 处理地址信息
      let processedAddress: any = null;
      if (orderData.deliveryAddress) {
        const addr = orderData.deliveryAddress;
        processedAddress = {
          id: addr.id || 0,
          name: addr.receiver || '',
          phone: addr.phone || '',
          province: addr.province || '',
          city: addr.city || '',
          district: addr.district || '',
          detail: addr.detailAddress || '',
          isDefault: addr.isDefault === 1
        };
      }
      
      // 处理商品项目
      const processedItems = (orderData.items || []).map((item: any) => ({
        id: item.id,
        foodId: item.foodId,
        foodName: item.foodName,
        foodImage: item.foodImage || '',
        price: item.price || 0,
        quantity: item.quantity || 1,
        subtotal: item.amount || (item.price * item.quantity) || 0,
        attributes: item.attributes || []
      }));
      
      // 组装订单信息
      orderInfo.value = {
        id: orderData.id,
        orderNo: orderData.orderNo || `ORDER-${orderData.id}`,
        userId: orderData.userId || 0,
        storeId: orderData.storeId || 0,
        storeName: orderData.storeName || '未知商家',
        totalAmount: orderData.totalAmount || 0,
        status: orderData.status,
        createTime: orderData.createdAt || orderData.createTime || '',
        items: processedItems,
        address: processedAddress
      };
      
      // 加载商家信息
      if (orderInfo.value.storeId) {
        await loadStoreInfo(orderInfo.value.storeId);
      }
    } else {
      ElMessage.error('订单数据格式错误');
    }
    
  } catch (error: any) {
    console.error('加载订单详情失败:', error);
    ElMessage.error(error.message || '加载订单详情失败');
  } finally {
    loading.value = false;
  }
};

// 加载商家信息
const loadStoreInfo = async (storeId: number) => {
  try {
    const response = await storeApi.getStoreDetail(storeId.toString());
    
    let storeData: any = null;
    if ((response as any).id) {
      storeData = response;
    } else if ((response as any).data && (response as any).data.id) {
      storeData = (response as any).data;
    } else if ((response as any).data && (response as any).data.data) {
      storeData = (response as any).data.data;
    }
    
    if (storeData && storeData.id) {
      storeInfo.value = {
        id: storeData.id,
        name: storeData.name || '未知商家',
        logo: storeData.logo || storeData.avatar || '',
        coverImage: storeData.coverImage || storeData.cover || ''
      };
    }
  } catch (error) {
    console.error('加载商家信息失败:', error);
  }
};

// 格式化时间
const formatTime = (time?: string): string => {
  if (!time) return '';
  const date = new Date(time);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  });
};

// 获取评分描述
const getRatingDesc = (rating: number): string => {
  if (rating >= 5) return '非常满意';
  if (rating >= 4) return '满意';
  if (rating >= 3) return '一般';
  if (rating >= 2) return '不满意';
  return '非常不满意';
};

// 切换快捷标签
const toggleTag = (tag: string) => {
  const index = selectedTags.value.indexOf(tag);
  if (index > -1) {
    selectedTags.value.splice(index, 1);
  } else {
    selectedTags.value.push(tag);
  }
  
  // 将选中的标签添加到评价内容中
  updateContentWithTags();
};

// 根据选中标签更新评价内容
const updateContentWithTags = () => {
  if (selectedTags.value.length > 0) {
    const tagsText = selectedTags.value.join('，');
    const currentContent = reviewForm.content.trim();
    
    if (!currentContent.includes(tagsText)) {
      reviewForm.content = currentContent ? `${currentContent}。${tagsText}` : tagsText;
    }
  }
};

// 图片上传前检查
const beforeImageUpload = (file: File) => {
  const isImage = file.type.startsWith('image/');
  const isLt5M = file.size / 1024 / 1024 < 5;
  
  if (!isImage) {
    ElMessage.error('只能上传图片文件!');
    return false;
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB!');
    return false;
  }
  return true;
};

// 处理图片变化
const handleImageChange = (file: UploadFile, fileList: UploadFiles) => {
  console.log('图片变化:', file, fileList);
  imageList.value = fileList;
};

// 处理图片删除
const handleImageRemove = (file: UploadFile, fileList: UploadFiles) => {
  console.log('删除图片:', file, fileList);
  imageList.value = fileList;
};

// 将文件转换为 base64
const convertFileToBase64 = (file: File): Promise<string> => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = () => {
      if (typeof reader.result === 'string') {
        resolve(reader.result);
      } else {
        reject(new Error('文件转换失败'));
      }
    };
    reader.onerror = () => reject(new Error('文件读取失败'));
    reader.readAsDataURL(file);
  });
};

// 提交评价
const submitReview = async () => {
  if (!reviewFormRef.value) return;
  
  try {
    // 表单验证
    await reviewFormRef.value.validate();
    
    // 确认提交
    await ElMessageBox.confirm('确定要提交评价吗？提交后不可修改。', '确认提交', {
      confirmButtonText: '确定提交',
      cancelButtonText: '再想想',
      type: 'info'
    });
    
    submitting.value = true;
    
    // 处理图片上传（将图片文件转换为 base64 或 URL 字符串）
    const imageUrls: string[] = [];
    
    // 处理已上传的图片
    for (const imageFile of imageList.value) {
      if (imageFile.raw) {
        try {
          // 如果是本地文件，转换为 base64
          const base64 = await convertFileToBase64(imageFile.raw);
          imageUrls.push(base64);
        } catch (error) {
          console.error('图片转换失败:', error);
        }
      } else if (imageFile.url) {
        // 如果已经是 URL，直接使用
        imageUrls.push(imageFile.url);
      }
    }
    
    // 提交评价数据
    const reviewData = {
      content: reviewForm.content,
      storeRating: reviewForm.storeRating,
      riderRating: reviewForm.riderRating,
      images: imageUrls.length > 0 ? imageUrls.join(',') : '' // 将图片 URL 数组转换为逗号分隔的字符串
    };
    
    await orderApi.reviewOrder(orderInfo.value.id!, reviewData);
    
    ElMessage.success('评价提交成功！');
    
    // 返回订单详情页
    router.replace(`/customer/order/${orderInfo.value.id}`);
    
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('提交评价失败:', error);
      ElMessage.error(error.message || '提交评价失败');
    }
  } finally {
    submitting.value = false;
  }
};

// 返回上页
const goBack = () => {
  router.back();
};
</script>

<style scoped>
.order-review-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  padding-bottom: 120px;
}

.page-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.back-btn {
  margin-right: 15px;
  color: #666;
}

.page-header h2 {
  margin: 0;
  color: #333;
  font-size: 20px;
}

/* 加载状态 */
.loading-container {
  text-align: center;
  padding: 80px 20px;
  color: #999;
}

.loading-container p {
  margin-top: 15px;
}

/* 通用区块样式 */
.order-info-section,
.review-form-section {
  background: white;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  overflow: hidden;
}

.section-title {
  display: flex;
  align-items: center;
  padding: 15px 20px;
  background: #fafafa;
  border-bottom: 1px solid #eee;
  font-weight: 600;
  color: #333;
  gap: 8px;
}

/* 订单信息 */
.order-summary {
  padding: 20px;
}

.store-info {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.store-logo {
  width: 50px;
  height: 50px;
  border-radius: 6px;
  margin-right: 15px;
}

.store-details {
  flex: 1;
}

.store-name {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 4px;
}

.order-time {
  font-size: 14px;
  color: #666;
}

.order-amount {
  font-size: 18px;
  font-weight: 600;
  color: #ff6600;
}

.items-summary {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 0;
  border-top: 1px solid #f0f0f0;
}

.items-count {
  color: #666;
  font-size: 14px;
}

.items-detail {
  border-top: 1px solid #f0f0f0;
  padding-top: 15px;
}

.item-detail {
  display: flex;
  align-items: center;
  padding: 10px 0;
  gap: 12px;
}

.item-detail:last-child {
  border-bottom: none;
}

.item-image {
  width: 40px;
  height: 40px;
  border-radius: 4px;
  flex-shrink: 0;
}

.item-info {
  flex: 1;
}

.item-name {
  font-size: 14px;
  color: #333;
  margin-bottom: 4px;
}

.item-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
}

.quantity {
  color: #666;
}

.price {
  color: #ff6600;
  font-weight: 500;
}

.image-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #f5f5f5;
  color: #ccc;
}

/* 评价表单 */
.review-form-section .el-form {
  padding: 20px;
}

.rating-container {
  display: flex;
  align-items: center;
  gap: 15px;
}

.rating-desc {
  color: #666;
  font-size: 14px;
}

.image-upload-section {
  width: 100%;
}

.upload-tip {
  margin-top: 10px;
  font-size: 12px;
  color: #999;
}

.quick-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.tag-item {
  cursor: pointer;
  transition: all 0.2s;
}

.tag-item:hover {
  transform: translateY(-1px);
}

/* 空状态 */
.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
}

/* 底部操作栏 */
.action-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  padding: 15px 20px;
  display: flex;
  gap: 15px;
  z-index: 100;
}

.cancel-btn,
.submit-btn {
  flex: 1;
  height: 44px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .order-review-container {
    padding: 15px;
  }
  
  .rating-container {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .store-info {
    align-items: flex-start;
  }
  
  .quick-tags {
    gap: 6px;
  }
  
  .action-bar {
    flex-direction: column;
    padding: 15px;
    gap: 10px;
  }
}
</style>
